#include "Writer.h"
#include <QMutexLocker>
#include <QDebug>

QMutex Writer::mutex(QMutex::NonRecursive);
int Writer::counter = 0;

Writer::Writer(int writingTime, int editTime, Library *library, QObject *parent) :
	QThread(parent), writingTime(writingTime), editTime(editTime), library(library), id(counter++)
{
}

void Writer::run()
{
	while (true) {
		qDebug() << "writer " << id;
		int whatToDo = qrand() % 2;
		if (whatToDo == 0 || myBooks.isEmpty()) {
			write();
		} else {
			edit();
		}
	}
}

void Writer::write()
{
	qDebug() << "Writer::write";
	if (tryToReserveSlot()) {
		writeBook();
		int bookId = library->addBook();
		myBooks.append(bookId);
	}
}

bool Writer::tryToReserveSlot()
{
	qDebug() << "Writer::tryToReserveSlot";
	QMutexLocker locker(&mutex);

	if (library->hasEmptySlots()) {
		library->reserveSlot();
		return true;
	} else {
		return false;
	}
}

void Writer::writeBook()
{
	qDebug() << "Writer::writeBook";
	msleep(writingTime);
}

void Writer::edit()
{
	int bookId = myBooks[qrand() % myBooks.size()];
	qDebug() << "Writer::edit " << bookId;
	library->getBook(bookId);
	editBook();
	library->returnBook(bookId);
}

void Writer::editBook()
{
	qDebug() << "Writer::editBook";
	msleep(editTime);
}

